package com.mitac.mcd.cs.mobiletracking.socketserver;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.mitac.mcd.cs.mobiletracking.socketserver.bean.TcpSocketBean;
import com.mitac.mcd.cs.mobiletracking.socketserver.util.BusinessUtil;
import com.mitac.mcd.cs.mobiletracking.socketserver.bean.NotificationMarkBean;

public class HealthCheck extends Thread{
	
	private MobileServerThread mobileServerThreadObj = null;
	public MobileServerThread getMobileServerThreadObj() {
		return mobileServerThreadObj;
	}

	public void setMobileServerThreadObj(MobileServerThread mobileServerThreadObj) {
		this.mobileServerThreadObj = mobileServerThreadObj;
	}

	private TcpSocketBean bean = null;
	private boolean _run = true;
	private List<NotificationMarkBean> notificationList = new ArrayList<NotificationMarkBean>();
	
	public List<NotificationMarkBean> getNotificationList() {
		return notificationList;
	}

	public void setNotificationList(List<NotificationMarkBean> notificationList) {
		this.notificationList = notificationList;
	}

	public HealthCheck(MobileServerThread obj) {
		mobileServerThreadObj = obj;
		bean = obj.tcb;
        this.start();
    }
	
	public void stopThread() {
        this._run = false;
        BusinessUtil.aLogger.info(mobileServerThreadObj.uuid+" health check thread已经停止...");
    }
	
	public void run() {
			while(this._run){
				try{
					if(mobileServerThreadObj.isAlive()){
						Date nowdate = new Date();
						if (!bean.isAutFlag()){
							BusinessUtil.aLogger.info("还未收到client信息，开始做接收首条信息超时验证");
							Date startdate = bean.getStartTime();
							int difftime = (int) ((nowdate.getTime()-startdate.getTime())/1000);
							if (difftime>MobileServer.tcpSocketAutTimeout){
								//超过了规定的时间，所以需要关闭创建的全部元素，socket object，
								//终止MobileServerThread线程，同时关闭对应的health check线程
								//log to db
								String note = "超过了接收首条数据的规定时间"+MobileServer.tcpSocketAutTimeout+"s，开始clear thread...";
								BusinessUtil.logException(mobileServerThreadObj.uuid, mobileServerThreadObj.user_id, mobileServerThreadObj.deviceType, mobileServerThreadObj.clientAddress, "E001",note);
								BusinessUtil.aLogger.info(note);
								breakConnectionDone();
								BusinessUtil.aLogger.info("完成clear thread...");
								stopThread();
							}
						}else{
							//开始做超时上传信息验证
							Date validateTime = null;
							//如果eachRecieveDataTime为null则说明aut成功后没有收到第一笔gps data，则以aut完成时间为戳记时间
							if (bean.getEachRecieveDataTime()==null){
								validateTime = bean.getFinishAutTime();
							}else{
								validateTime = bean.getEachRecieveDataTime();
							}
							//如果validateTime仍然为null，说明正在aut的过程当中，此时不做校验，设置为当前时间
							if (validateTime==null) validateTime = nowdate;
							long difftime = nowdate.getTime()-validateTime.getTime();
							if (difftime>mobileServerThreadObj.interval*1000){//单位ms
								try{
									mobileServerThreadObj.socket.sendUrgentData(0xFF);
		                        }catch(Exception ex){
		                        	String note = mobileServerThreadObj.socket+"与socket server连接已经断开...";
		                        	BusinessUtil.aLogger.info(note);
		                        	BusinessUtil.afterCloseSocketDone(mobileServerThreadObj);
		                        	breakConnectionDone();
		                        	//log to db
									BusinessUtil.logException(mobileServerThreadObj.uuid, mobileServerThreadObj.user_id, mobileServerThreadObj.deviceType, mobileServerThreadObj.clientAddress, "E006",note);
		                        	stopThread();
		                        }
							}
							if (difftime>mobileServerThreadObj.gpsUploadIntervalTime*1000){//单位ms
								String note = "gps upload间隔时间超过了规定时间"+mobileServerThreadObj.gpsUploadIntervalTime+"s，开始执行afterCloseSocketDone，然后clear thread...";
								BusinessUtil.aLogger.info(note);
								BusinessUtil.afterCloseSocketDone(mobileServerThreadObj);
								//log to db
								BusinessUtil.logException(mobileServerThreadObj.uuid, mobileServerThreadObj.user_id, mobileServerThreadObj.deviceType, mobileServerThreadObj.clientAddress, "E002",note);
								//BusinessUtil.afterCloseSocketDone(mobileServerThreadObj);
								breakConnectionDone();
								BusinessUtil.aLogger.info("完成clear thread...");
								stopThread();
							}
						}
					}else{
						stopThread();
					}
					
				}catch (IOException e) {
					e.printStackTrace();
				}
				//间隔5s执行
				try {
					Thread.sleep(5*1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
	}
	
	/**
	 * 首先关闭线程的I/O连接，保证线程不被网络阻塞
	 * 设置while共享变量为false
	 * 调用interrupt方法，假如线程被阻塞，则被唤醒
	 * @throws IOException
	 */
	public void breakConnectionDone() throws IOException{
		mobileServerThreadObj.stopThread();
		//mobileServerThreadObj.interrupt();
		if (!mobileServerThreadObj.socket.isClosed()) mobileServerThreadObj.socket.close();
		BusinessUtil.aLogger.info("完成interrupt thread...");
	}
	
}
